#include <unistd.h>
#include <zcm/zcm-cpp.hpp>
#include "HELLO.hpp"
#include <iostream>
#include <string>
#include <chrono>
#include <string.h>
#include <hiredis/hiredis.h>
using namespace std;
#define IP "127.0.0.1"
#define PORT 6379
#define CHANNEL "TEST"
int main(int argc, char *argv[])
{
    char ip[16] = IP, channel[20] = CHANNEL;
    int port = PORT;
    char buf[200];
    switch (argc)
    {
    case 4:
        strcpy(channel, argv[3]);
    case 3:
        port = stoi(argv[2]);
    case 2:
        strcpy(ip, argv[1]);
    }
    // 连接服务器
    redisContext *context = redisConnect(ip, port);
    redisReply *reply = NULL;
    if (context->err)
    {
        std::cout << "can not connect to redisserver" << endl;
        std::cout << "reason:" << context->errstr << endl;
        redisFree(context);
        context = NULL;
        return 0;
    }

    // 订阅消息
    reply = (redisReply *)redisCommand(context, "SUBSCRIBE %s", channel);
    if (NULL == reply || reply->type != REDIS_REPLY_ARRAY) //订阅成功返回一个数组标识
    {
        std::cout << "subscribe failed!" << endl;
        freeReplyObject(reply);
        redisFree(context);
        context = NULL;
        return 0;
    }
    freeReplyObject(reply);

    // 创建zcm对象
    HELLO recv_msg{};
    //阻塞等待订阅消息
    while (true)
    {
        void *_reply = nullptr;
        if (redisGetReply(context, &_reply) != REDIS_OK)
        {
            continue;
        }
        reply = (redisReply *)_reply;
        // 0 类型 1 channel 2 内容
        recv_msg.decode(reply->element[2]->str, 0, reply->element[2]->len);
        chrono::milliseconds ms = chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now().time_since_epoch());
        long int use_time = (long int)ms.count() - stol(recv_msg.time);
        cout << "recv message: " << recv_msg.str << " from " << reply->element[1]->str << " use time: " << use_time << endl;
        freeReplyObject(reply);
        std::cout << "***************" << std::endl;
    }
    redisFree(context);
    context = NULL;
    return 0;
}